from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import images

from django.utils import simplejson

from atoz import BaseHandler
from views import ActualView, TemplateHelper
import models
import config

class AdminHandler(BaseHandler):
    def __init__(self):
        self.template_values = {'app': config.APP,
                         'admin':True,
                         'person': config.CONTACT,
                         'logout_url': users.create_logout_url('/'),
                        }
        self.template = TemplateHelper()
        self.view = ActualView()
        
    def get(self):
        action = self.request.get('a')
        key = self.request.get('k')
        type = self.request.get('t')
        
        if action == 'edit':
            if type == 'question':
                pass
            if type == 'topic':
                pass
        
        if action == 'add':
            if type == 'question':
                self.template_values['question_form'] = models.QuestionsForm()
                self.response.out.write(self.template.render_output('admin/question_answer', self.template_values))
                return
            if type == 'topic':
                self.template_values['topic_form'] = models.TopicForm()
                self.response.out.write(self.template.render_output('admin/topic_help', self.template_values))
                return
        if action == 'uploadimage':
            self.response.out.write(self.template.render_output('admin/imageupload', self.template_values))
            return
        
        if not action and not key and not type:
            self.template_values['content'] = self.view.all_help()
                
        self.response.out.write(self.template.render_output('admin/admin', self.template_values))

    def post(self):
        action = self.request.get('a')
        key = self.request.get('k')
        type = self.request.get('t')
        
        if not action and not type:
            self.redirect('/admin/?m=issue')
        
        if action == 'edit':
            if type == 'question':
                pass
            if type == 'topic':
                pass
        
        if action == 'add':
            if type == 'question':
                raw_quest = models.QuestionsForm(data = self.request.POST)
                
                tags = map(lambda x: x.strip(), self.request.get('tags').split(','))
                try:
                    #raw_quest.clean_data['tags'] = tags
                    raw_quest.data['tags'] = tags
                except:
                    raise
                if raw_quest.is_valid():
                    raw_quest.clean_data['tags'] = tags
                    k = raw_quest.save()
                    message = 'Question Saved Successfully'
                    models.Tags.increment_count(tags)
                    models.save_tags(tags)
                else:
                    self.template_values['question_form'] = raw_quest
                    self.response.out.write(self.template.render_output('admin/question_answer', 
                                                        self.template_values))
                    return
            if type == 'topic':
                raw_topic = models.TopicForm(data = self.request.POST)
                if raw_topic.is_valid():
                    raw_topic.save()
                    message = 'Topic Saved Successfully'
                else: 
                    self.template_values['topic_form'] = raw_topic
                    self.response.out.write(self.template.render_output('admin/topic_help',
                                                        self.template_values))
                    return
        
        if action == 'uploadimage' and type == 'upload':
            result = {}
            try:
                image_ = self.request.get('pic')
                my_image = images.Image(image_)
                w = my_image.width
                h = my_image.height
                if h > 400 or w > 400:
                    aspect_ratio = w*1.0/h
                    if aspect_ratio > 1:
                        new_w = 400
                        new_h = int(400/aspect_ratio)
                    else:
                        new_h = 400
                        new_w = int(400*aspect_ratio)
                    my_image.resize(new_w, new_h)
                    k = models.Picture(pic = my_image.execute_transforms()).put()
                k = models.Picture(pic = image_).put()
                result['success'] = 1
                result['k'] = str(k)
                result['align'] = self.request.get('imagealign')
            except:
                result['success'] = 0
                raise
            self.response.out.write(simplejson.dumps(result))
            return
        
        try:
            self.redirect('/admin/?m='+message)
        except:
            self.redirect('/admin/?i=00')